import datetime
import time
from dateutil.parser import parse


# 字符串转datetime
def str_to_datetime(str):
    return parse(str)


# datetime按照指定格式转字符串
def datetime_to_str(date=None, fmt='%Y-%m-%d %H:%M:%S'):
    if date is None:
        date = datetime.datetime.now()
    return date.strftime(fmt)


# datetime转y-m-d
def datetime_to_ymd(date=None):
    if date is None:
        date = datetime.datetime.now()
    return datetime_to_str(date, '%Y-%m-%d')


# datetime转y-m-d h:m:s
def datetime_to_ymdhms(date=None):
    if date is None:
        date = datetime.datetime.now()
    return datetime_to_str(date, '%Y-%m-%d %H:%M:%S')


# 加减天数
def add_days(today, days_num):
    days = datetime.timedelta(days=days_num)
    new_day = today + days
    return new_day


# 获取昨日同一时间. 可以获取指定日期的前一天
def get_yesterday(today=None):
    if today is None:
        today = datetime.datetime.now()
    return add_days(today, -1)


# 获取零点
def get_000000(now=None):
    if now is None:
        now = datetime.datetime.now()
    d = now - datetime.timedelta(hours=now.hour, minutes=now.minute, seconds=now.second,
                                 microseconds=now.microsecond)
    return d


# 获取23:59:59
def get_235959(now=None):
    if now is None:
        now = datetime.datetime.now()
    d = add_days(now, 1)
    d = get_000000(d)
    d = d - datetime.timedelta(microseconds=1, milliseconds=1)
    return d


if __name__ == "__main__":
    yesterday = get_yesterday()
    print("昨天凌晨:" + datetime_to_ymdhms(get_000000(yesterday)))
    print("今天凌晨:" + datetime_to_ymdhms(get_000000()))

    print("昨天23:59:59:" + datetime_to_ymdhms(get_235959(yesterday)))
    print("今天23:59:59:" + datetime_to_ymdhms(get_235959()))

    print("当前时间yyyy-mm-dd hh:mm:ss格式:" + datetime_to_ymdhms())
    print("当前时间yyyy-mm-dd格式:" + datetime_to_ymd())

    print("昨天时间yyyy-mm-dd hh:mm:ss格式:" + datetime_to_ymdhms(yesterday))
    print("昨天时间yyyy-mm-dd格式:" + datetime_to_ymd(yesterday))

    for i in range(0, 100):
        print(get_yesterday())
        time.sleep(1)
